package com.google.cbmgraph;

import java.util.ArrayList;
import com.google.cbmgraph.data.DataSourceList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MenuFragment  extends ListFragment {
	/** object that's passed from the intro screen with the database name information */
	static DataSourceList dataNames;
	private OnGraphSelectedListener graphSelectedListener;
	
	/** Called when the activity is first created. This populates the list. I have it select dummy data is a server is out of reach*/
        @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

		Intent intent = getActivity().getIntent();
		Bundle b = intent.getExtras();
		DataSourceList dataNames = (DataSourceList) b.getParcelable("datasourcelist");
	
        ArrayList<String> temp = new ArrayList<String>();
        
        if (dataNames !=null){
            for (int i = 0; i < dataNames.size(); i++){
            	temp.add(dataNames.get(i));
            }
        }else{
        	for (int i = 0; i < 25; i++){
        	temp.add("example data set "+(i+1));
        	}
        }
		ArrayAdapter<String> names = new ArrayAdapter<String>(getActivity(), R.layout.menu_cbm, temp);
		
		setListAdapter(names);
   }
    	/** interface for streamlining passing information. */
    public interface OnGraphSelectedListener {
        public void onGraphSelected(String item);
    }
	/** Called when the activity is first attached. */

    @Override
    public void onAttach(Activity activity) {
    	super.onAttach(activity);
        try {
            graphSelectedListener = (OnGraphSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnGraphSelectedListener");
        }
    }
	/** Called when an item is clicked, sadly I wasn't able to find a way to select
	 * WebGraph for when in fragment mode
	 */
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
		String item = (String) getListAdapter().getItem(position);
		Log.d("MenuFragment", item+" was picked");
		if (item != null){
			Log.d("MenuFragment", item+" was picked! Telling listener");
			graphSelectedListener.onGraphSelected(item);
		}
	}
}
